<template>
  <div class="user-management">
    <!-- 顶部操作栏 -->
    <div class="action-bar">
      <div class="search-box">
        <input 
          type="text" 
          v-model="searchQuery" 
          placeholder="搜索用户名/邮箱"
          @input="handleSearch"
        >
        <i class="fas fa-search"></i>
      </div>
      <div class="filters">
        <select v-model="roleFilter">
          <option value="">全部角色</option>
          <option value="user">普通用户</option>
          <option value="admin">管理员</option>
        </select>
        <select v-model="statusFilter">
          <option value="">全部状态</option>
          <option value="active">正常</option>
          <option value="blocked">已封禁</option>
        </select>
      </div>
      <button class="add-btn" @click="showAddModal = true">
        <i class="fas fa-plus"></i>
        添加用户
      </button>
    </div>

    <!-- 用户列表 -->
    <div class="user-table">
      <table>
        <thead>
          <tr>
            <th>用户ID</th>
            <th>用户名</th>
            <th>邮箱</th>
            <th>角色</th>
            <th>状态</th>
            <th>注册时间</th>
            <th>最后登录</th>
            <th>操作</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="user in filteredUsers" :key="user._id">
            <td>{{ user._id }}</td>
            <td>{{ user.username }}</td>
            <td>{{ user.email }}</td>
            <td>
              <span class="role-tag" :class="user.role">
                {{ user.role === 'admin' ? '管理员' : '普通用户' }}
              </span>
            </td>
            <td>
              <span class="status-tag" :class="user.status">
                {{ user.status === 'active' ? '正常' : '已封禁' }}
              </span>
            </td>
            <td>{{ formatDate(user.createdAt) }}</td>
            <td>{{ formatDate(user.lastLoginAt) }}</td>
            <td>
              <div class="action-buttons">
                <button class="view-btn" @click="viewUserDetail(user)">
                  <i class="fas fa-eye"></i>
                </button>
                <button class="edit-btn" @click="handleEdit(user)">
                  <i class="fas fa-edit"></i>
                </button>
                <button 
                  class="toggle-btn" 
                  :class="user.status"
                  @click="toggleStatus(user)"
                >
                  <i :class="user.status === 'active' ? 'fas fa-ban' : 'fas fa-check'"></i>
                </button>
              </div>
            </td>
          </tr>
        </tbody>
      </table>
    </div>

    <!-- 分页 -->
    <div class="pagination">
      <button 
        :disabled="currentPage === 1"
        @click="currentPage--"
      >
        <i class="fas fa-chevron-left"></i>
      </button>
      <span>第 {{ currentPage }} 页</span>
      <button 
        :disabled="currentPage === totalPages"
        @click="currentPage++"
      >
        <i class="fas fa-chevron-right"></i>
      </button>
    </div>

    <!-- 添加/编辑用户弹窗 -->
    <div class="modal" v-if="showAddModal || showEditModal">
      <div class="modal-content">
        <div class="modal-header">
          <h3>{{ showEditModal ? '编辑用户' : '添加用户' }}</h3>
          <button class="close-btn" @click="closeModal">
            <i class="fas fa-times"></i>
          </button>
        </div>
        <div class="modal-body">
          <form @submit.prevent="handleSubmit">
            <div class="form-group">
              <label>用户名</label>
              <input 
                type="text" 
                v-model="formData.username" 
                required
                :disabled="showEditModal"
              >
            </div>
            <div class="form-group">
              <label>邮箱</label>
              <input type="email" v-model="formData.email" required>
            </div>
            <div class="form-group" v-if="!showEditModal">
              <label>密码</label>
              <input type="password" v-model="formData.password" required>
            </div>
            <div class="form-group">
              <label>角色</label>
              <select v-model="formData.role" required>
                <option value="user">普通用户</option>
                <option value="admin">管理员</option>
              </select>
            </div>
            <div class="form-group">
              <label>状态</label>
              <select v-model="formData.status" required>
                <option value="active">正常</option>
                <option value="blocked">封禁</option>
              </select>
            </div>
            <div class="form-actions">
              <button type="button" class="cancel-btn" @click="closeModal">取消</button>
              <button type="submit" class="submit-btn">
                {{ showEditModal ? '保存修改' : '添加用户' }}
              </button>
            </div>
          </form>
        </div>
      </div>
    </div>

    <!-- 用户详情弹窗 -->
    <div class="modal" v-if="showDetailModal">
      <div class="modal-content">
        <div class="modal-header">
          <h3>用户详情</h3>
          <button class="close-btn" @click="showDetailModal = false">
            <i class="fas fa-times"></i>
          </button>
        </div>
        <div class="modal-body" v-if="selectedUser">
          <div class="detail-section">
            <h4>基本信息</h4>
            <div class="detail-row">
              <span class="label">用户ID：</span>
              <span>{{ selectedUser._id }}</span>
            </div>
            <div class="detail-row">
              <span class="label">用户名：</span>
              <span>{{ selectedUser.username }}</span>
            </div>
            <div class="detail-row">
              <span class="label">邮箱：</span>
              <span>{{ selectedUser.email }}</span>
            </div>
            <div class="detail-row">
              <span class="label">角色：</span>
              <span class="role-tag" :class="selectedUser.role">
                {{ selectedUser.role === 'admin' ? '管理员' : '普通用户' }}
              </span>
            </div>
            <div class="detail-row">
              <span class="label">状态：</span>
              <span class="status-tag" :class="selectedUser.status">
                {{ selectedUser.status === 'active' ? '正常' : '已封禁' }}
              </span>
            </div>
          </div>

          <div class="detail-section">
            <h4>个人资料</h4>
            <div class="detail-row">
              <span class="label">姓名：</span>
              <span>{{ selectedUser.profile?.name || '-' }}</span>
            </div>
            <div class="detail-row">
              <span class="label">手机：</span>
              <span>{{ selectedUser.profile?.phone || '-' }}</span>
            </div>
            <div class="detail-row">
              <span class="label">地址：</span>
              <span>{{ selectedUser.profile?.address || '-' }}</span>
            </div>
          </div>

          <div class="detail-section">
            <h4>账户信息</h4>
            <div class="detail-row">
              <span class="label">注册时间：</span>
              <span>{{ formatDate(selectedUser.createdAt) }}</span>
            </div>
            <div class="detail-row">
              <span class="label">最后登录：</span>
              <span>{{ formatDate(selectedUser.lastLoginAt) }}</span>
            </div>
          </div>

          <div class="detail-section">
            <h4>订单统计</h4>
            <div class="stats-grid">
              <div class="stat-card">
                <div class="stat-value">{{ selectedUser.stats?.totalOrders || 0 }}</div>
                <div class="stat-label">总订单数</div>
              </div>
              <div class="stat-card">
                <div class="stat-value">¥{{ selectedUser.stats?.totalSpent || 0 }}</div>
                <div class="stat-label">消费总额</div>
              </div>
              <div class="stat-card">
                <div class="stat-value">{{ selectedUser.stats?.returnRate || '0%' }}</div>
                <div class="stat-label">退货率</div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { userApi } from '@/api'
import type { User } from '@/types'

// 状态变量
const users = ref<User[]>([])
const searchQuery = ref('')
const roleFilter = ref('')
const statusFilter = ref('')
const currentPage = ref(1)
const totalPages = ref(1)
const showAddModal = ref(false)
const showEditModal = ref(false)
const showDetailModal = ref(false)
const selectedUser = ref<User | null>(null)

// 表单数据
const formData = ref({
  username: '',
  email: '',
  password: '',
  role: 'user',
  status: 'active'
})

// 过滤用户列表
const filteredUsers = computed(() => {
  return users.value.filter(user => {
    const matchQuery = user.username.toLowerCase().includes(searchQuery.value.toLowerCase()) ||
                      user.email.toLowerCase().includes(searchQuery.value.toLowerCase())
    const matchRole = !roleFilter.value || user.role === roleFilter.value
    const matchStatus = !statusFilter.value || user.status === statusFilter.value
    return matchQuery && matchRole && matchStatus
  })
})

// 格式化日期
const formatDate = (date: string) => {
  if (!date) return '-'
  return new Date(date).toLocaleString('zh-CN')
}

// 搜索处理
const handleSearch = () => {
  currentPage.value = 1
  fetchUsers()
}

// 查看用户详情
const viewUserDetail = (user: User) => {
  selectedUser.value = user
  showDetailModal.value = true
}

// 编辑用户
const handleEdit = (user: User) => {
  selectedUser.value = user
  formData.value = {
    ...user,
    password: ''
  }
  showEditModal.value = true
}

// 切换用户状态
const toggleStatus = async (user: User) => {
  const newStatus = user.status === 'active' ? 'blocked' : 'active'
  const message = newStatus === 'blocked' ? '封禁' : '解封'
  
  if (!confirm(`确定要${message}用户"${user.username}"吗？`)) return

  try {
    await userApi.updateStatus(user._id, newStatus)
    const index = users.value.findIndex(u => u._id === user._id)
    if (index !== -1) {
      users.value[index].status = newStatus
    }
  } catch (error) {
    console.error('Failed to update user status:', error)
  }
}

// 提交表单
const handleSubmit = async () => {
  try {
    if (showEditModal.value && selectedUser.value) {
      await userApi.update(selectedUser.value._id, formData.value)
      const index = users.value.findIndex(u => u._id === selectedUser.value?._id)
      if (index !== -1) {
        users.value[index] = { ...selectedUser.value, ...formData.value }
      }
    } else {
      const response = await userApi.create(formData.value)
      users.value.unshift(response.data)
    }
    closeModal()
  } catch (error) {
    console.error('Failed to save user:', error)
  }
}

// 关闭弹窗
const closeModal = () => {
  showAddModal.value = false
  showEditModal.value = false
  selectedUser.value = null
  formData.value = {
    username: '',
    email: '',
    password: '',
    role: 'user',
    status: 'active'
  }
}

// 获取用户列表
const fetchUsers = async () => {
  try {
    const response = await userApi.getList({
      page: currentPage.value,
      role: roleFilter.value,
      status: statusFilter.value
    })
    users.value = response.data
    totalPages.value = Math.ceil(response.total / response.pageSize)
  } catch (error) {
    console.error('Failed to fetch users:', error)
  }
}

// 初始化
fetchUsers()
</script>

<style scoped>
.user-management {
  padding: 24px;
}

.action-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}

.search-box {
  position: relative;
  width: 300px;
}

.search-box input {
  width: 100%;
  padding: 8px 32px 8px 12px;
  border: 1px solid #d9d9d9;
  border-radius: 4px;
}

.search-box i {
  position: absolute;
  right: 12px;
  top: 50%;
  transform: translateY(-50%);
  color: #999;
}

.filters {
  display: flex;
  gap: 16px;
}

.filters select {
  padding: 8px;
  border: 1px solid #d9d9d9;
  border-radius: 4px;
}

.add-btn {
  padding: 8px 16px;
  background-color: #1890ff;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 8px;
}

.user-table {
  background: white;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.06);
}

table {
  width: 100%;
  border-collapse: collapse;
}

th, td {
  padding: 12px;
  text-align: left;
  border-bottom: 1px solid #f0f0f0;
}

th {
  background: #fafafa;
  font-weight: 500;
  color: #666;
}

.role-tag {
  padding: 2px 8px;
  border-radius: 10px;
  font-size: 12px;
}

.role-tag.admin {
  background: #f9f0ff;
  color: #722ed1;
}

.role-tag.user {
  background: #e6f7ff;
  color: #1890ff;
}

.status-tag {
  padding: 2px 8px;
  border-radius: 10px;
  font-size: 12px;
}

.status-tag.active {
  background: #f6ffed;
  color: #52c41a;
}

.status-tag.blocked {
  background: #fff1f0;
  color: #ff4d4f;
}

.action-buttons {
  display: flex;
  gap: 8px;
}

.action-buttons button {
  padding: 4px 8px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.view-btn {
  background: #e6f7ff;
  color: #1890ff;
}

.edit-btn {
  background: #f9f0ff;
  color: #722ed1;
}

.toggle-btn.active {
  background: #fff1f0;
  color: #ff4d4f;
}

.toggle-btn.blocked {
  background: #f6ffed;
  color: #52c41a;
}

.pagination {
  margin-top: 24px;
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 16px;
}

.pagination button {
  padding: 4px 8px;
  border: 1px solid #d9d9d9;
  border-radius: 4px;
  background: white;
  cursor: pointer;
}

.pagination button:disabled {
  background: #f5f5f5;
  cursor: not-allowed;
}

.modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.modal-content {
  background: white;
  border-radius: 8px;
  width: 600px;
  max-width: 90%;
  max-height: 90vh;
  overflow-y: auto;
}

.modal-header {
  padding: 16px 24px;
  border-bottom: 1px solid #f0f0f0;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.modal-header h3 {
  margin: 0;
}

.close-btn {
  border: none;
  background: none;
  font-size: 18px;
  cursor: pointer;
  color: #999;
}

.modal-body {
  padding: 24px;
}

.form-group {
  margin-bottom: 16px;
}

.form-group label {
  display: block;
  margin-bottom: 8px;
  color: #666;
}

.form-group input,
.form-group select {
  width: 100%;
  padding: 8px;
  border: 1px solid #d9d9d9;
  border-radius: 4px;
}

.form-actions {
  display: flex;
  justify-content: flex-end;
  gap: 16px;
  margin-top: 24px;
}

.submit-btn {
  padding: 8px 16px;
  background: #1890ff;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.cancel-btn {
  padding: 8px 16px;
  border: 1px solid #d9d9d9;
  border-radius: 4px;
  background: white;
  cursor: pointer;
}

.detail-section {
  margin-bottom: 24px;
}

.detail-section h4 {
  margin: 0 0 16px 0;
  color: #333;
}

.detail-row {
  display: flex;
  margin-bottom: 8px;
}

.detail-row .label {
  width: 100px;
  color: #666;
}

.stats-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 16px;
}

.stat-card {
  padding: 16px;
  background: #fafafa;
  border-radius: 4px;
  text-align: center;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: #1890ff;
  margin-bottom: 4px;
}

.stat-label {
  font-size: 12px;
  color: #666;
}
</style> 